import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    public int[] smallestK(int[] arr, int k) {
        int[] ret=new int[k];
        if (arr == null || k<=0){
            return ret;
        }
        PriorityQueue<Integer> priorityQueue=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        for (int i = 0; i < arr.length; i++) {
            if (k>0){
                priorityQueue.offer(arr[i]);
                k--;
            }else {
                if (priorityQueue.peek()>arr[i]){
                    priorityQueue.poll();
                    priorityQueue.offer(arr[i]);
                }
            }
        }
        for (int i = 0; i < ret.length; i++) {
            ret[i]=priorityQueue.poll();
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] arr={1,3,5,7,2,4,6,8};
        Solution s1=new Solution();
       int [] ret= s1.smallestK(arr,4);
        System.out.println(Arrays.toString(ret));
    }
}